import React, { useRef, useEffect, useState } from 'react'
import ReactToPrint from 'react-to-print'
import Barcode from 'react-barcode'
import './index.less'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { getSpuDevPrintListBySpuDevIds } from '@/api/goods'
import { PrintBoxLabelVO, ProductSpuDevPrintVO } from './types'
import { getBoxLabelPrintInfo, printBoxLabels } from '@/api/purchase'
import dayjs from 'dayjs'
import { notification } from 'antd'
import { downloadByUrl } from '@/utils/util'
export default function PdfView() {
  const componentRef = useRef(null)
  const navigate = useNavigate()
  const [query] = useSearchParams()
  const [listData, setlistData] = useState<ProductSpuDevPrintVO[]>([])
  const type = query.get('type')
  enum typeEnum {
    STYLE = '1', //款式打印
    BOXMARKCODE = '2', //箱唛条码打印
    BOXMARK = '3', //箱唛打印
    BOXMARKBYBOXLABEL = '4', //箱唛打印
  }
  const { state } = useLocation()
  console.log(state, 'state')
  useEffect(() => {
    type == typeEnum.STYLE && getList()
    type == typeEnum.BOXMARK && getListBox()
    type == typeEnum.BOXMARKBYBOXLABEL && getListBoxByBoxLabel()
  }, [])
  const getList = async () => {
    const res = await getSpuDevPrintListBySpuDevIds<ProductSpuDevPrintVO>({ spuDevIds: state?.params || [] }).catch(
      (err) => {
        if (err?.response?.status === 401) {
          navigate('/login', { replace: true })
        }
      },
    )
    setlistData(res?.data || [])
    console.log(res?.data, 'rrr')
  }
  const getListBox = async () => {
    const res = await printBoxLabels<ProductSpuDevPrintVO>({ reserveInvoiceCodes: state?.params || [] }).catch(
      (err) => {
        if (err?.response?.status === 401) {
          navigate('/login', { replace: true })
        }
      },
    )
    setlistData(res?.data || [])
    if (res?.code === 820000 && res?.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const getListBoxByBoxLabel = async () => {
    const res = await getBoxLabelPrintInfo<PrintBoxLabelVO>({ boxLabelCodes: state?.params || [] }).catch((err) => {
      if (err?.response?.status === 401) {
        navigate('/login', { replace: true })
      }
    })
    setlistData(res?.data || [])
    if (res?.code === 820000 && res?.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleDownLoad = () => {
    downloadByUrl('https://sop.7sef.com/prod/20241120/箱唛纸张大小打印设置_1732080926463.pdf')
  }

  return (
    <>
      <div className="print-page-fixed">
        <ReactToPrint
          trigger={() => <button className="myselfbutton">点击打印</button>}
          content={() => componentRef.current}
        />
      </div>
      {(type == typeEnum.BOXMARK || type == typeEnum.BOXMARKBYBOXLABEL) && (
        <div className="download_file_btn" onClick={handleDownLoad}>
          <button className="cssbuttons-io-button">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
              <path fill="none" d="M0 0h24v24H0z"></path>
              <path
                fill="currentColor"
                d="M1 14.5a6.496 6.496 0 0 1 3.064-5.519 8.001 8.001 0 0 1 15.872 0 6.5 6.5 0 0 1-2.936 12L7 21c-3.356-.274-6-3.078-6-6.5zm15.848 4.487a4.5 4.5 0 0 0 2.03-8.309l-.807-.503-.12-.942a6.001 6.001 0 0 0-11.903 0l-.12.942-.805.503a4.5 4.5 0 0 0 2.029 8.309l.173.013h9.35l.173-.013zM13 12h3l-4 5-4-5h3V8h2v4z"
              ></path>
            </svg>
            <span>如何设置打印格式</span>
          </button>
        </div>
      )}
      <div ref={componentRef} id="pdfViewId">
        {/* 款式打印 */}
        {type == typeEnum.STYLE && (
          <div className="style_print_container">
            <div className="style_print_spec">
              {listData?.map((item: any, index: number) => {
                return (
                  <div className="gsp_item" key={index}>
                    <div className="gspi_img_box">
                      <img src={item?.mainPicFileId || ''} alt="" />
                    </div>
                    <div className="gspi_info_box">
                      <table>
                        <thead>
                          <tr>
                            <td className="bold">大类</td>
                            <td>{item?.bigClassName || '-'}</td>
                            <td className="bold">上市时间</td>
                            <td>{item?.releaseSeasonDate || '-'}</td>
                          </tr>
                          <tr>
                            <td className="bold">款式名称</td>
                            <td colSpan={3} style={{ textAlign: 'left' }}>
                              {item?.spuName || '-'}
                            </td>
                          </tr>
                          <tr>
                            <td className="bold">商品等级</td>
                            <td>{item?.productLevel || '-'}</td>
                            <td className="bold">版型</td>
                            <td>{item?.patternType || '-'}</td>
                          </tr>
                          <tr>
                            <td className="bold">助记码</td>
                            <td>{item?.designCode || '-'}</td>
                            <td className="bold">颜色</td>
                            <td>{item?.colorDetailName || '-'}</td>
                          </tr>
                          <tr>
                            <td className="bold">尺码范围</td>
                            <td colSpan={3}>
                              {item?.sizeRangeList?.reduce((acc: string, item: any, index: number) => {
                                return acc + (index === 0 ? '' : ',') + item?.sizeDetailName
                              }, '')}
                            </td>
                          </tr>
                          <tr>
                            <td className="bold">吊牌价</td>
                            <td colSpan={3}>{item?.originSalePrice || '-'}</td>
                          </tr>
                        </thead>
                      </table>
                    </div>
                    <div className="gspi_code_box">
                      <div>
                        {item?.productSeries || '-'}
                        {item?.factorySpuCode ? ' - ' + item.factorySpuCode : ''}
                      </div>
                      <div className="gspicb_con">
                        <Barcode value={item?.designCode} margin={10} font="26px" />
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        )}
        {/* 箱唛条码打印 */}
        {type == typeEnum.BOXMARKCODE && (
          <div className="box_markcode_print_container">
            <div className="box_markcode_print">
              {state?.params && state?.params.length > 0
                ? state?.params?.map((item: any, index: number) => {
                    return (
                      <div className="gsp_item" key={index}>
                        <div className="gspi_info_box">
                          <div>商品条码：{item?.skuCode}</div>
                          <div>箱规：{item?.inBoxNum * item?.outBoxNum}</div>
                        </div>
                        <div className="gspi_code_box">
                          <div className="gspicb_con">
                            <Barcode value={item?.boxLabelCode} margin={10} font="26px" />
                          </div>
                        </div>
                      </div>
                    )
                  })
                : null}
            </div>
          </div>
        )}
        {/* 箱唛打印 */}
        {(type == typeEnum.BOXMARK || type == typeEnum.BOXMARKBYBOXLABEL) && (
          <div className="box_mark_print">
            {listData && listData.length > 0
              ? listData?.map((item: any, index: number) => {
                  return (
                    <div className="standard_outbox" key={index}>
                      <div className="standard">
                        <div className="line">
                          <div className="line_left">标准箱唛</div>
                        </div>
                        <div className="line">
                          <div className="line_left">装箱标识</div>
                          <div className="line_right">
                            {item?.boxLabelTypeName === '尾箱'
                              ? '★★ ' + item?.boxLabelTypeName + ' ★★'
                              : item?.boxLabelTypeName}
                          </div>
                        </div>
                        <div className="line">
                          <div className="line_left">仓位号</div>
                          <div className="line_right">{item?.warehouse}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">供应商</div>
                          <div className="line_right">{item?.supplierCode}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">大类</div>
                          <div className="line_right">{item?.bigClassName}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">细类</div>
                          <div className="line_right">{item?.tinyClassName}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">款号</div>
                          <div className="line_right">{item?.spuCode}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">装箱数量</div>
                          <div className="line_right">{item?.loadQtyStr}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">颜色</div>
                          <div className="line_right">{item?.colorDetailName}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">尺码</div>
                          <div className="line_right">{item?.size}</div>
                        </div>
                        <div className="line innerbarcode" style={{ height: item?.boxLabelCode ? 110 : 220 }}>
                          <Barcode
                            value={item?.skuCode || ''}
                            width={3}
                            height={item?.boxLabelCode ? 50 : 60}
                            displayValue={true}
                            fontSize={item?.boxLabelCode ? 26 : 34}
                            font="26px"
                          />
                        </div>
                        <div className="line">
                          <div className="line_left">预约单号</div>
                          <div className="line_right">{item?.reserveInvoiceCode}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">装箱编号</div>
                          <div className="line_right">{item.loadCode}</div>
                        </div>
                        <div className="line">
                          <div className="line_left">净重/毛重</div>
                          <div className="line_right">{item?.netWeight + ' / ' + item?.grossWeight}</div>
                        </div>
                        {item?.boxLabelCode ? (
                          <div className="line innerbarcode">
                            <div className="line_left">箱唛号</div>
                            <div className="line_right innerbarcode">
                              <Barcode
                                value={item?.boxLabelCode || ''}
                                width={3}
                                height={50}
                                fontSize={26}
                                font="26px"
                              />
                            </div>
                          </div>
                        ) : null}
                        <div className="line">
                          <div className="line_left">打印时间</div>
                          <div className="line_right">{dayjs().format('YYYY/MM/DD')}</div>
                        </div>
                      </div>
                    </div>
                  )
                })
              : null}
          </div>
        )}
      </div>
    </>
  )
}
